// 节流
function throttle(func, delay) {
  let timer = null; // 用于存放计时器的变量

  return function () {
    if (!timer) {
      func.apply(this, arguments); // 调用传入的函数并将参数传递进去

      timer = setTimeout(() => {
        clearTimeout(timer); // 清除计时器

        timer = null; // 重置计时器为null
      }, delay);
    }
  };
}

function formatDate(date, isObj?: boolean) {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');

  return isObj ? {
    year,
    month,
    day,
    hours,
    minutes,
    seconds
  } : `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

// 睡眠，外层调用需要 async await
const sleep = (duration?: number) =>
new Promise((res) => {
  setTimeout(res, duration ?? 1000)
})

// 扁平化数组指定key 层级
const flatArrByKey = (arr: any[], flatKey: string, level?: number) => {
  if (!Array.isArray(arr) || !flatKey) return [];
  const newArr: any[] = [];
  const flatArr = (fArr: any[], fKey: string, fLevel: number) => {
    fArr.forEach(item => {
      newArr.push(Object.keys(item).reduce((result, key) => {
        if (key !== flatKey) {
          result[key] = item[key];
        } else if ((!level || fLevel < level) && Array.isArray(item?.[flatKey])) {
          flatArr(item?.[flatKey], fKey, fLevel + 1)
        }
        return result;
      }, {}))
    })
  }
  flatArr(arr, flatKey, 1)
  return newArr;
}

const getSpaceColor = (startColor: string, endColor: string, step: number = 1) => {
  const allStep: number = 100;
  const hexToRgb = (hex: string) => {
    let str = hex.replace("#", "");
    if (str.length % 3) {
      throw new Error('请输入hex格式的字符串！')
    }
    let count = str.length / 3;
    let power = 6 / str.length;
    let r = parseInt("0x" + str.substring(0 * count, 1 * count))**power;
    let g = parseInt("0x" + str.substring(1 * count, 2 * count))**power;
    let b = parseInt("0x" + str.substring(2 * count))**power;
    // return `rgb(${r}, ${g}, ${b})`;
    return { r, g, b }
  }
  const startCol = hexToRgb(startColor);
  const endCol = hexToRgb(endColor);
  const stepColor = (start: number, end: number) => start + (end - start) * step / allStep;
  return { r: stepColor(startCol.r, endCol.r), g: stepColor(startCol.g, endCol.g), b: stepColor(startCol.b, endCol.b) }
}

const getSpaceColArr = (startColor: string, endColor: string, step: number = 1)=>{
  const allStep: number = 100;
  const isFull:boolean = allStep % step === 0;
  const arrLength:number = Math.ceil(allStep / step)
  return new Array(arrLength).fill(1).map((item,index)=>getSpaceColor(startColor,endColor,step*index))
}

function RGBToHex(r, g, b) {
  var hex = "#" + ((1 << 24) | (r << 16) | (g << 8) | b).toString(16).slice(1);
  return hex;
}

const func = {
  throttle,
  formatDate,
  sleep,
  flatArrByKey,
  getSpaceColor,
  getSpaceColArr,
  RGBToHex
}

export default func;